<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/6/26
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper;


use Closure;
use paper\http\Request;
use paper\http\Response;
use paper\server\Server;

class Middleware implements Server
{

    //待处理的中间件队列
    protected $queue = [];
    protected $middleware;

    public function __construct(App $app)
    {
    }

    public function register($middleware)
    {
        $this->middleware = $middleware;
    }

    /**
     * @param Request $request
     * @param Closure $destination
     * @return bool|Response
     */
    public function then(Request $request, Closure $destination)
    {
        $this->add($destination);
        return call_user_func($this->resolve(), $request);
    }


    /**
     * @param $middleware
     * =     */
    public function add($middleware)
    {
        $this->queue[] = $middleware;
    }

    /**
     * @param array $middleware
     */
    public function import(array $middleware)
    {
        foreach ($middleware as $item) {
            $this->add($item);
        }
    }

    /**
     * 执行中间件
     * @return Closure
     */
    public function resolve()
    {
        return function (Request $request) {
            $middleware = array_shift($this->queue);
            if (is_callable($middleware)) {
                return $middleware($request, $this->resolve());
            } else {
                return call_user_func_array([$this->make($middleware), 'handle'], [$request, $this->resolve()]);
            }
        };
    }

    private function make($call)
    {
        $middleware = new $call();
        if (is_callable([$middleware, 'handle'], false)) {
            return $middleware;
        }
        return false;
    }

}